package com.yeskery.nut.core;

import java.io.Serializable;

/**
 * 键值对类
 * @author sprout
 * 2019-03-13 16:37
 * @version 1.0
 */
public class KeyAndValue<K, V> implements Serializable, Cloneable {

	/** 键 */
	private final K key;

	/** 值 */
	private final V value;

	/**
	 * 构建一个键值对对象
	 * @param key 键
	 * @param value 值
	 */
	public KeyAndValue(K key, V value) {
		if (key == null || value == null) {
			throw new NullPointerException("key and value can not be null.");
		}
		this.key = key;
		this.value = value;
	}

	/**
	 * 获取键
	 * @return 键
	 */
	public K getKey() {
		return key;
	}

	/**
	 * 获取值
	 * @return 值
	 */
	public V getValue() {
		return value;
	}

	@Override
	public int hashCode() {
		return key.hashCode() + value.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj instanceof KeyAndValue) {
			KeyAndValue<?, ?> keyAndValue = (KeyAndValue<?, ?>) obj;
			return key.equals(keyAndValue.key) && value.equals(keyAndValue.value);
		}
		return false;
	}

	@Override
	public String toString() {
		return "KeyAndValue{" +
				"key='" + key + '\'' +
				", value='" + value + '\'' +
				'}';
	}

	@Override
	@SuppressWarnings("unchecked")
	public KeyAndValue<K, V> clone() {
		try {
			return (KeyAndValue<K, V>) super.clone();
		} catch (CloneNotSupportedException e) {
			throw new NutException(e);
		}
	}
}
